﻿/* ***********************************************
 * Author		:  kingthy
 * Email		:  kingthy@gmail.com
 * Description	:  KTUtility
 *
 * ***********************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using KT.Core.Extensions;
using System.Net;
using System.Security.Cryptography;
using System.IO;
namespace KT.Core
{
    /// <summary>
    /// 实用类
    /// </summary>
    public static class Utility
    {
        #region IP地址函数块
        /// <summary>
        /// 判断是否是有效的IP V4地址
        /// </summary>
        /// <param name="ip">数字格式的地址，如"255.255.255.245"</param>
        /// <returns>如果是IPV4的数字表示格式，则返回true否则返回false</returns>
        public static bool IsValidIP(string ip)
        {
            string[] segments = ip.Split(new char[]{'.'}, 4);
            if (segments.Length != 4) return false;
            foreach (var seg in segments)
            {
                int b = seg.As<int>(-1);
                if (b < 0 || b > 255) return false;
            }
            return true;
        }

        /// <summary>
        /// 将某个IP地址转为Int32值
        /// </summary>
        /// <param name="ip">数字格式的地址，如"255.255.255.245"</param>
        /// <returns></returns>
        public static int IPToInt32(string ip)
        {
            IPAddress address = null;
            if (IPAddress.TryParse(ip, out address))
            {
                return BitConverter.ToInt32(address.GetAddressBytes(), 0);
            }
            else
            {
                return -1;
            }
        }
        /// <summary>
        /// 将某个IP地址转为Int64值
        /// </summary>
        /// <param name="ip">数字格式的地址，如"255.255.255.245"</param>
        /// <returns></returns>
        public static long IPToInt64(string ip)
        {
            int value = IPToInt32(ip);
            if (value == -1) return -1L;
            return value & 0xffffffffL;
        }
        /// <summary>
        /// 将某个Int32值转换为IP地址的标准格式
        /// </summary>
        /// <param name="address"></param>
        /// <returns>数字格式的地址，如"255.255.255.245"</returns>
        public static string ToIPAddress(int address)
        {
            return ToIPAddress(address & 0xffffffffL);
        }
        /// <summary>
        /// 将某个Int64值转换为IP地址的标准格式
        /// </summary>
        /// <param name="address"></param>
        /// <returns>数字格式的地址，如"255.255.255.245"</returns>
        public static string ToIPAddress(long address)
        {
            if ((address < 0L) || (address > 0xffffffffL))
                return "Unknown";
            return new IPAddress(address).ToString();
        }
        #endregion

        #region 是否有效的文件扩展名
        /// <summary>
        /// 判断文件是否符合某些扩展名
        /// </summary>
        /// <param name="file">要判断的文件地址,支持文件格式(如:c:\file.jpg)或URL格式(如:http://localhost/file.jpg)</param>
        /// <param name="fileExt">允许的文件扩展名，多个扩展名之间使用“;”号分隔,如 ".jpg;.gif;.bmp"</param>
        /// <returns>如果文件的扩展名是<paramref name="fileExt"/>定义的其中之一，则返回true，否则返回false</returns>
        public static bool IsValidFileExt(string file, string fileExt)
        {
            if (string.IsNullOrEmpty(file)) return false;
            if (string.IsNullOrEmpty(fileExt)) return true;

            string ext = VirtualPathUtility.GetExtension(file);
            if (string.IsNullOrEmpty(ext)) return false;

            return fileExt.IsContain(ext, ";", true);
        }
        #endregion

        #region 随机函数块
        /// <summary>
        /// 随机数生成器
        /// </summary>
        private static Random _Random;
        /// <summary>
        /// 随机数生成器
        /// </summary>
        public static Random Random
        {
            get
            {
                if (_Random == null)
                {
                    lock (typeof(Utility))
                    {
                        if (_Random == null)
                            _Random = Utility.CreateRandom();
                    }
                }
                return _Random;
            }
        }
        /// <summary>
        /// 生成一个新的随机数生成器
        /// </summary>
        public static Random CreateRandom()
        {
            return new Random(CreateRndSeed());
        }

        /// <summary>
        /// 获取新的随机种子数
        /// </summary>
        /// <returns></returns>
        public static int CreateRndSeed()
        {
            byte[] rndBytes = new byte[4];
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            rng.GetBytes(rndBytes);
            return BitConverter.ToInt32(rndBytes, 0);
        }
        /// <summary>
        /// 获取数字与英文字母(大写)列的随机码
        /// </summary>
        /// <param name="length">要获取的长度</param>
        /// <returns></returns>
        public static string CreateRndCode(int length)
        {
            return CreateRndCode("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", length);
        }
        /// <summary>
        /// 获取随机码
        /// </summary>
        /// <param name="codeChars">随机码字符字符列表，如“0123456789”</param>
        /// <param name="length">要获取的随机码长度</param>
        /// <returns>随机码字符</returns>
        public static string CreateRndCode(string codeChars, int length)
        {
            //默认的值
            if (string.IsNullOrEmpty(codeChars) || length < 1) return string.Empty; ;

            int formatlength = codeChars.Length - 1;
            StringBuilder codes = new StringBuilder(length);
            int i;
            var rnd = Utility.Random;
            for (i = 1; i <= length; i++)
            {
                codes.Append(codeChars[rnd.Next(0, formatlength)]);
            }
            return codes.ToString();
        }
        #endregion

        #region 路径操作函数块
        /// <summary>
        /// 判断地址是否是绝对路径，如网络地址“http://www.baidu.com”；本地地址：“c:\test.txt”
        /// </summary>
        /// <param name="path">要判断的路径地址，如网络地址“http://www.baidu.com”（绝对）、“/test/file.txt”（相对）</param>
        /// <returns></returns>
        public static bool IsAbsolutePath(string path)
        {
            //绝对地址，则直接返回
            Uri uri;
            return Uri.TryCreate(path, UriKind.Absolute, out uri);
        }
        /// <summary>
        /// 将某个路径转换为绝对路径
        /// </summary>
        /// <param name="path">路径地址，如果
        /// 地址为相对路径，则将转换为相对于当前应用程序的路径。
        /// (a、如果在WinFrom应用程序下，则是相对于程序所在目录;
        /// b、如果是在Web应用程序下，则是相对于Web站点所在目录)
        /// 2、地址为绝对路径，则原样返回
        /// </param>
        /// <returns></returns>
        public static string ToAbsolutePath(string path)
        {
            if (string.IsNullOrEmpty(path)) path = "/";
            
            //绝对地址，则直接返回
            if (IsAbsolutePath(path)) return path;

            //相对路径。
            var request = WebContext.Request.Current;
            if (request != null)
            {
                //Web应用程序
                return request.MapPath(path);
            }
            else
            {
                //应用程序
                return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, path.TrimStart(new char[]{'~','\\','/'}));
            }
        }
        #endregion
    }
}
